﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Text;
using System.Configuration;

namespace WebSite.Core
{
    public class CarrefourLoginHelper
    {
        private static byte[] key = ASCIIEncoding.ASCII.GetBytes( ConfigurationManager.AppSettings["EncryptKey"] );
        private static byte[] iv = key;

        /// <summary>
        /// 字符串的MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MD5( string str )
        {
            str = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile( str, "MD5" );
            return str;
        }

        ///// <summary>
        ///// 去除非法字串
        ///// </summary>
        ///// <param name="strChar">原字串</param>
        ///// <returns>过滤过的字串</returns>
        //public static string ReplaceBadChar( string strChar )
        //{
        //    if (strChar == null || strChar.Trim() == "")
        //    {
        //        return "";
        //    }
        //    else
        //    {
        //        strChar = Regex.Replace( strChar, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase );
        //        strChar = Regex.Replace( strChar, @"<iframe[^>]*?>.*?</iframe>", "", RegexOptions.IgnoreCase );
        //        strChar = Regex.Replace( strChar, @"(<meta(.[^>]*)>)", "", RegexOptions.IgnoreCase );
        //        strChar = Regex.Replace( strChar, @" href *= *[\s\S]*script *:", "", RegexOptions.IgnoreCase );
        //        strChar = Regex.Replace( strChar, @"alert", "", RegexOptions.IgnoreCase );
        //        strChar = Regex.Replace( strChar, @"script", "", RegexOptions.IgnoreCase );
        //        strChar = strChar.Replace( "'", "''" );
        //        strChar = strChar.Replace( ">", "&gt;" );
        //        strChar = strChar.Replace( "<", "&lt;" );
        //        return strChar.Trim();
        //    }
        //}

        /// <summary>
        /// DES加密。
        /// </summary>
        /// <param name="inputString">输入字符串。</param>
        /// <returns>加密后的字符串。</returns>
        public static string DESEncrypt( string inputString )
        {
            MemoryStream ms = null;
            CryptoStream cs = null;
            StreamWriter sw = null;

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                ms = new MemoryStream();
                cs = new CryptoStream( ms, des.CreateEncryptor( key, iv ), CryptoStreamMode.Write );
                sw = new StreamWriter( cs );
                sw.Write( inputString );
                sw.Flush();
                cs.FlushFinalBlock();
                return Convert.ToBase64String( ms.GetBuffer(), 0, (int)ms.Length );
            }
            finally
            {
                if (sw != null) sw.Close();
                if (cs != null) cs.Close();
                if (ms != null) ms.Close();
            }
        }

        /// <summary>
        /// DES解密。
        /// </summary>
        /// <param name="inputString">输入字符串。</param>
        /// <returns>解密后的字符串。</returns>
        public static string DESDecrypt( string inputString )
        {
            MemoryStream ms = null;
            CryptoStream cs = null;
            StreamReader sr = null;

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                ms = new MemoryStream( Convert.FromBase64String( inputString ) );
                cs = new CryptoStream( ms, des.CreateDecryptor( key, iv ), CryptoStreamMode.Read );
                sr = new StreamReader( cs );
                return sr.ReadToEnd();
            }
            finally
            {
                if (sr != null) sr.Close();
                if (cs != null) cs.Close();
                if (ms != null) ms.Close();
            }
        }

        /// <summary>
        /// 调用主站ws，验证加密后的用户名密码
        /// </summary>
        /// <param name="enuid"></param>
        /// <param name="enpwd"></param>
        /// <returns></returns>
        public static string CheckLogin( string uid, string pwd )
        {
            BasePage page = HttpContext.Current.Handler as BasePage;
            if (page == null)
            {
                return "";
            }

            if (string.IsNullOrEmpty( uid ) || string.IsNullOrEmpty( pwd ))
            {
                page.AlertMessageBack( "请填写用户名和密码" );
            }

            string enuid = HttpUtility.UrlEncode( DESEncrypt( uid ) );
            string enpwd = MD5( DESEncrypt( pwd ) );

            carrefourws.ws ws_main = new carrefourws.ws();
            ws_main.Url = ConfigurationManager.AppSettings["carrefourwsurl"];
            return ws_main.LoginByEncode( enuid, enpwd );

            /* var bll = new Maticsoft.BLL.CarrefourCover.Account();
            var entity = bll.GetModelList( "UserName='" + username.SqlFilter() + "' AND Passwrod = '" + password.SqlFilter() + "'" );

            if (entity.Count == 0)
            {
                page.AlertMessageBack( "用户名或密码错误" );
            }
*/
        }
    }
}